﻿using KamRemakeRemake.GameObjects;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace KamRemakeRemake.Graphics {
    public class AnimatedSprite {
        /// <summary>
        /// The game sends 30 updates per second, and we will switch to the next frame every 8 updates
        /// </summary>
        private const int UPDATESPERFRAME = 8;

        public Texture2D Texture { get; set; }
        public int TotalRows { get; set; }
        public int Columns { get; set; }
        public int? ActiveRow { get; set; }

        private int currentFrame;
        private int totalFrames;
        private int currentUpdate;

        public AnimatedSprite(Texture2D texture, int totalRows, int columns) {
            Texture = texture;
            TotalRows = totalRows;
            Columns = columns;
            currentFrame = 0;
            totalFrames = TotalRows * Columns;
        }

        public void Update(GameTime gameTime) {
            currentUpdate++;
            if (currentUpdate == UPDATESPERFRAME) {
                currentUpdate = 0;

                currentFrame++;
                if (currentFrame == totalFrames)
                    currentFrame = 0;
            }
        }

        public void Draw(SpriteBatch spriteBatch, Vector2 location) {
            int width = Texture.Width / Columns;
            int height = Texture.Height / TotalRows;

            // if the active row is specified use that one, if not use the 
            int row = ActiveRow.HasValue ? ActiveRow.Value : (int)((float)currentFrame / (float)Columns);
            
            int column = currentFrame % Columns;

            Rectangle sourceRectangle = new Rectangle(width * column, height * row, width, height);
            Rectangle destinationRectangle = new Rectangle((int)location.X - (int)Camera.Instance.Position.X,
                                                           (int)location.Y - (int)Camera.Instance.Position.Y,
                                                           width, 
                                                           height);

            spriteBatch.Draw(Texture, destinationRectangle, sourceRectangle, Color.White);
        }
    }
}
